package com.example.nocodesqlapi.controller;

import com.example.nocodesqlapi.model.SqlConfig;
import com.example.nocodesqlapi.service.SqlConfigService;
import com.example.nocodesqlapi.service.SqlExecuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 动态API控制器，根据配置的SQL提供接口服务
 */
@RestController
public class DynamicApiController {
    
    @Autowired
    private SqlConfigService sqlConfigService;
    
    @Autowired
    private SqlExecuteService sqlExecuteService;
    
    /**
     * 处理所有GET请求
     */
    @GetMapping("/**")
    public ResponseEntity<?> handleGetRequest(HttpServletRequest request) {
        return handleRequest(request, "GET");
    }
    
    /**
     * 处理所有POST请求
     */
    @PostMapping("/**")
    public ResponseEntity<?> handlePostRequest(
            HttpServletRequest request, 
            @RequestBody(required = false) Map<String, Object> bodyParams) {
        return handleRequest(request, "POST", bodyParams);
    }
    
    /**
     * 处理所有PUT请求
     */
    @PutMapping("/**")
    public ResponseEntity<?> handlePutRequest(
            HttpServletRequest request, 
            @RequestBody(required = false) Map<String, Object> bodyParams) {
        return handleRequest(request, "PUT", bodyParams);
    }
    
    /**
     * 处理所有DELETE请求
     */
    @DeleteMapping("/**")
    public ResponseEntity<?> handleDeleteRequest(
            HttpServletRequest request, 
            @RequestBody(required = false) Map<String, Object> bodyParams) {
        return handleRequest(request, "DELETE", bodyParams);
    }
    
    /**
     * 统一处理请求
     */
    private ResponseEntity<?> handleRequest(
            HttpServletRequest request, 
            String method, 
            Map<String, Object>... bodyParams) {
        
        // 获取请求路径
        String requestPath = request.getRequestURI();
        
        // 查询对应的SQL配置
        Optional<SqlConfig> sqlConfigOpt = sqlConfigService.getEnabledSqlConfigByApiPath(requestPath);
        if (sqlConfigOpt.isEmpty()) {
            return ResponseEntity.notFound().build();
        }
        
        SqlConfig sqlConfig = sqlConfigOpt.get();
        
        // 验证请求方法是否匹配
        if (!sqlConfig.getMethod().equalsIgnoreCase(method)) {
            return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body("不支持的请求方法，期望: " + sqlConfig.getMethod());
        }
        
        // 收集所有参数
        Map<String, Object> params = collectAllParams(request, bodyParams.length > 0 ? bodyParams[0] : null);
        
        // 执行SQL并返回结果
        try {
            Map<String, Object> result = sqlExecuteService.executeSql(sqlConfig, params);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "error", e.getMessage()
            ));
        }
    }
    
    /**
     * 收集所有参数（路径参数、查询参数、请求体参数）
     */
    private Map<String, Object> collectAllParams(HttpServletRequest request, Map<String, Object> bodyParams) {
        Map<String, Object> params = new HashMap<>();
        
        // 添加查询参数
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String name = paramNames.nextElement();
            params.put(name, request.getParameter(name));
        }
        
        // 添加请求体参数
        if (bodyParams != null && !bodyParams.isEmpty()) {
            params.putAll(bodyParams);
        }
        
        return params;
    }
}
